<?php

namespace app\admin\controller\facrm\analysis;

use app\admin\model\AuthGroup;
use app\common\controller\Backend;
use fast\Tree;
use think\Db;


/**
 *排行榜
 */
class Ranking extends Backend
{
    protected $model = null;
    protected $searchFields = 'id,username,nickname';
    protected $groupList = [];

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('Admin');

        $this->childrenAdminIds = $this->auth->getChildrenAdminIds(true);
        $this->childrenGroupIds = $this->auth->getChildrenGroupIds(true);
        $this->groupList = $groupList = collection(AuthGroup::where('id', 'in', $this->childrenGroupIds)->select())->toArray();
        Tree::instance()->init($groupList);
        $groupdata = [];
        if ($this->auth->isSuperAdmin()) {
            $result = Tree::instance()->getTreeList(Tree::instance()->getTreeArray(0));
            foreach ($result as $k => $v) {
                $groupdata[$v['id']] = $v['name'];
            }
        } else {

            $result = [];
            $groups = $this->auth->getGroups();
            foreach ($groups as $m => $n) {
                $childlist = Tree::instance()->getTreeList(Tree::instance()->getTreeArray($n['id']));
                foreach ($childlist as $k => $v) {
                    $groupdata[$v['id']] = $v['name'];
                }

            }

        }

        $this->view->assign('groupdata', $groupdata);
        $this->assignconfig('groupdata', $groupdata);
        $this->assignconfig("admin", ['id' => $this->auth->id]);

    }

    /**
     * 合同排行
     */
    public function contract()
    {
        if ($this->request->isAjax()) {
            $contractModel = new \app\admin\model\facrm\Contract();

            $filter = $this->request->get("filter", '');
            $filter = (array)json_decode($filter, true);
            $filter_c = [];
            if (isset($filter['search_time'])) {
                $filter['search_time'] = str_replace(' - ', ',', $filter['search_time']);
                $arr = array_slice(explode(',', $filter['search_time']), 0, 2);
                if (count($arr)<2)return $this->error(__("时间参数有误"));
                $filter_c['order_time'] = ['between time', $arr];
            }

            $childrenAdminIds =$this->getChildrenAdminIds($filter);
            if ($childrenAdminIds){
                $contractModel->where('order_admin_id', 'in', $childrenAdminIds);
            }

            $order = "count";
            if (isset($filter['type_id'])) {
                switch ($filter['type_id']) {
                    case 1:
                        $order = "count";
                        break;
                    case 2:
                        $order = "money";
                        break;
                }
            }

            $lists = $contractModel->where('check_status', 2)->where($filter_c)
                ->field('COUNT(*) AS count, sum(money) as money,order_admin_id')
                ->group('order_admin_id')->limit(0, 10)->order($order, 'desc')->fetchSql(false)
                ->select();
            $j = 1;
            foreach ($lists as $row) {
                // $row->orderAdmin;
                if ($row->orderAdmin){
                    $row->orderAdmin->hidden(['password', 'token', 'salt']);
                }
                $row['index'] = $j;
                $j++;
            }
            $result = array("total" => count($lists), "rows" => $lists);

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     *回款排行
     */
    public function receivables()
    {
        if ($this->request->isAjax()) {
            $receivablesModel = new \app\admin\model\facrm\contract\Receivables();

            $filter = $this->request->get("filter", '');
            $filter = (array)json_decode($filter, true);
            $filter_c = [];
            if (isset($filter['search_time'])) {
                $filter['search_time'] = str_replace(' - ', ',', $filter['search_time']);
                $arr = array_slice(explode(',', $filter['search_time']), 0, 2);
                if (count($arr)<2)return $this->error(__("时间参数有误"));
                $filter_c['return_time'] = ['between time', $arr];
            }

            $childrenAdminIds =$this->getChildrenAdminIds($filter);
            if ($childrenAdminIds){
                $receivablesModel->where('order_admin_id', 'in', $childrenAdminIds);
            }

            $order = "money";
            if (isset($filter['type_id'])) {
                switch ($filter['type_id']) {
                    case 1:
                        $order = "count";
                        break;
                    case 2:
                        $order = "money";
                        break;
                }
            }

            $lists = $receivablesModel->where('check_status', 2)->where($filter_c)
                ->field('COUNT(*) AS count, sum(money) as money,order_admin_id')
                ->group('order_admin_id')->limit(0, 10)->order($order, 'desc')->fetchSql(false)
                ->select();
            $j = 1;
            foreach ($lists as $row) {
                if ($row->orderAdmin){
                    $row->orderAdmin->hidden(['password', 'token', 'salt']);
                }
                $row['index'] = $j;
                $j++;
            }
            $result = array("total" => count($lists), "rows" => $lists);

            return json($result);
        }
        return $this->view->fetch('contract');
    }

    /**
     * 新客排名
     * @return string|\think\response\Json|void
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function addCustomer()
    {
        if ($this->request->isAjax()) {
            $customerModel = new \app\admin\model\facrm\Customer();

            $filter = $this->request->get("filter", '');
            $filter = (array)json_decode($filter, true);
            $filter_c = [];
            if (isset($filter['search_time'])) {
                $filter['search_time'] = str_replace(' - ', ',', $filter['search_time']);
                $arr = array_slice(explode(',', $filter['search_time']), 0, 2);
                if (count($arr)<2)return $this->error(__("时间参数有误"));
                $filter_c['create_time'] = ['between time', $arr];
            }

            $childrenAdminIds =$this->getChildrenAdminIds($filter);
            if ($childrenAdminIds){
                $customerModel->where('create_user_id', 'in', $childrenAdminIds);
            }

            $order = "count";
            $lists = $customerModel->where($filter_c)
                ->field('COUNT(*) AS count,create_user_id')
                ->group('create_user_id')->limit(0, 10)->order($order, 'desc')->fetchSql(false)
                ->select();
            $j = 1;
            foreach ($lists as $row) {
                // $row->orderAdmin;
                $row->createUser;
                $row['index'] = $j;
                $j++;
            }
            $result = array("total" => count($lists), "rows" => $lists);

            return json($result);
        }
        return $this->view->fetch('contract');
    }

    /**
     * 跟进排名
     */
    public function record()
    {
        if ($this->request->isAjax()) {
            $recordModel = new \app\admin\model\facrm\Record();

            $filter = $this->request->get("filter", '');
            $filter = (array)json_decode($filter, true);
            $filter_c = [];
            if (isset($filter['search_time'])) {
                $filter['search_time'] = str_replace(' - ', ',', $filter['search_time']);
                $arr = array_slice(explode(',', $filter['search_time']), 0, 2);
                if (count($arr)<2)return $this->error(__("时间参数有误"));

                $filter_c['create_time'] = ['between time', $arr];
            }
            $childrenAdminIds =$this->getChildrenAdminIds($filter);
            if ($childrenAdminIds){
                $recordModel->where('create_user_id', 'in', $childrenAdminIds);
            }
            $order = "count";
            $filter['type_id'] = isset($filter['type_id']) ? $filter['type_id'] : 1;
            switch ($filter['type_id']) {
                case 1:
                    $order = "count";//跟进次数
                    break;
                case 2:
                    $order = "total";//客户数量select create_user_id, count(distinct types_id) as count,count(*) as aa from fa_facrm_record group by create_user_id ORDER BY count desc  LIMIT 0,10
                    break;
                default:
                    return $this->error(__("访问有误"));
            }
            $lists = $recordModel->where('types', "customer")->where($filter_c)
                ->field("count(distinct types_id) AS total,create_user_id,types_id,count(*) as count")
                ->group('create_user_id')->limit(0, 10)->order($order, 'desc')->fetchSql(false)
                ->select();
            $j = 1;
            foreach ($lists as $row) {
                if ($row->createUser){
                    $row->createUser->hidden(['password', 'token', 'salt']);
                }
                $row['index'] = $j;
                $j++;
            }

            $result = array("total" => count($lists), "rows" => $lists);

            return json($result);
        }
        return $this->view->fetch('contract');
    }

    /**
     * 产品排名
     * @return \think\response\Json|void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function product()
    {
        if ($this->request->isAjax()) {
            $productModel = new \app\admin\model\facrm\contract\Product();
            $productModel->alias('p')->join('facrm_contract c','c.id=p.contract_id');
            $filter = $this->request->get("filter", '');
            $filter = (array)json_decode($filter, true);
            $filter_c = [];
            if (isset($filter['search_time'])) {
                $filter['search_time'] = str_replace(' - ', ',', $filter['search_time']);
                $arr = array_slice(explode(',', $filter['search_time']), 0, 2);
                if (count($arr)<2)return $this->error(__("时间参数有误"));
                $start_time=strtotime($arr[0]);
                $end_time=strtotime($arr[1]);
                $productModel->where("c.order_time BETWEEN {$start_time} AND {$end_time}");

            }
            $childrenAdminIds =$this->getChildrenAdminIds($filter);
            if ($childrenAdminIds){
                $productModel->where('order_admin_id', 'in', $childrenAdminIds);
            }
            $order = "count";
            $filter['type_id'] = isset($filter['type_id']) ? $filter['type_id'] : 1;
            switch ($filter['type_id']) {
                case 1:
                    $order = "count";//销售数量
                    break;
                case 2:
                    $order = "total";//销售金额
                    break;
                default:
                    return $this->error(__("访问有误"));
            }
            $lists = $productModel->where('check_status',2)
                ->field("count(*) as count,sum(subtotal) as total,product_id,p.name,product_id")
                ->limit(0, 10)->order($order, 'desc')->fetchSql(false)->group('product_id')
                ->select();
            $j = 1;
            foreach ($lists as $row) {
                $row['index'] = $j;
                $j++;
            }

            $result = array("total" => count($lists), "rows" => $lists);

            return json($result);
        }
        return $this->view->fetch('contract');
    }

    protected function getChildrenAdminIds($filter)
    {
        $childrenAdminIds = [];
        if (isset($filter['group_id'])) {
            $childrenAdminIds = [];
            if ($filter['group_id'] > 0) {
                Tree::instance()->init($this->groupList);
                $groupIds = Tree::instance()->getChildrenIds($filter['group_id'], true);

                $authGroupList = \app\admin\model\AuthGroupAccess::
                field('uid,group_id')
                    ->where('group_id', 'in', $groupIds)
                    ->select();
                foreach ($authGroupList as $k => $v) {
                    if (in_array($v['uid'], $childrenAdminIds)) continue;
                    $childrenAdminIds[] = $v['uid'];
                }
                if (!$childrenAdminIds) {

                    return $this->error("该组下面没有成员");
                }
            }
        }
        return  $childrenAdminIds;
    }

}
